// Add semicolon to prevent IIFE from being passed as argument to concatenated code.
;
// UMD (Universal Module Definition)
// see https://github.com/umdjs/umd/blob/master/returnExports.js
(function (root, factory) {
    /* global define, exports, module */
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(factory);
    } else if (typeof exports === 'object') {
        // Node. Does not work with strict CommonJS, but
        // only CommonJS-like enviroments that support module.exports,
        // like Node.
        module.exports = factory();
    } else {
        // Browser globals (root is window)
        root.PageGrid = factory();
  }
}(this, function () {
	/**<pre>分页的表格
	 *包括title, body, button, check, pager
	 *setting={
	 *	id:'',
	 *	style:{pageGrid:'style'},
	 *	attachId:'',	//创建好的pageGrid要放在那个地方，attachId的标签在创建后会被删除。
	 *	minHeight:430px,
	 *	checkOpt:true|false,			//是否有复选框列
	 *	radioOpt:true|false,
	 *	keyColumn:'',					//主键列
	 *	columns:[{title:'',code:'',render:function(value){}}],	//列信息
	 *	buttons:[{name,type,show:function(record){return true;},onclick:function(record){}}],	//每行的操作按钮
	 *	dataURL:'',	//数据来源的url
	 *	page:{enable:true, pageSize:,mini:false } //mini:true pageSize固定
	 *	data:{list:[],page:{totalPage,totalCount,pageSize,pageNo,nextPage,prePage},param},
	 *	afterLoadData:function(){},
	 *	onClickRecord:function(){}
	 *}
	 *</pre>*/
	var PageGrid=function(setting,data){
		this.setting={
			maxFieldLength:32,
			minHeight:'200px',
			style:{},
			page:{
				enable:true,
				pageSize:10,
				pageNo:1,
				mini:false
			}
		};
		$.extend(true,this.setting,setting);
		//list:[];map:<key,record>;page:totalPage,totalCount,pageSize,pageNo,nextPage,prePage;Param
		this.data={list:[],map:{},param:{}};
		data=data||{};
		this.refine(data.list||[],data.page||{pageSize:this.setting.page.pageSize,pageNo:this.setting.page.pageNo},data.param);
		this.init();
	};
	PageGrid.prototype={
		setColumns:function(fields){
			this.setting.columns=fields;
			var $headRow=$('.headRow',this.$id);
			$headRow.empty();
			var html=[];
			if(this.setting.checkOpt)
				html.push('					<th><input type="checkbox" class="allCheck"></th>');
			else 
				html.push('<th></th>');
			$.each(this.setting.columns,function(){
				html.push('					<th>'+this.title+'</th>');
			});
			if(this.setting.buttons&&this.setting.buttons.length>0)
				html.push('					<th>操作</th>');
			$headRow.html(html.join(''));
		},
		render:function(){
			//先创建容器div
			this.id=this.setting.id;
			this.$id=$('<div class="PageGrid" style="'+this.setting.style.pageGrid+'" id="'+this.id+'"></div> ');
			
			this.renderTable();
			this.renderPager();
			this.$id.append(this.$table);
			this.setting.page.enable&&this.$id.append(this.$pager);
			
			//附加到attachId上，否则body
			if(this.setting.attachId)
			{
				var $attachId=$('#'+this.setting.attachId);
				$attachId.after(this.$id);
				$attachId.remove();
			}	
			else
				$('body').append(this.$id);
	},
	miniPagerTemplate:'<nav><ul class="pagination" style="margin:0px;">'
		+'		<li><a href="javascript:void(0)" class="btnFirst">首页</a></li>'
		+'		<li><a href="javascript:void(0)" class="btnPre">上一页</a></li>'
		+'		<li><a href="javascript:void(0)" class="btnNext">下一页</a></li>'
		+'		<li><a href="javascript:void(0)" class="btnLast">尾页</a></li>'
		+'		<li><div style="padding: 2px 5px; float: left">'
		+'				<input type="text" maxlength="5" onkeyup="this.value=this.value.replace(/\D/g,\'\');"'
		+'					style="width: 50px; display: inline-block;" class="input-sm form-control pageNo"/>'
		+'					页/<span class="totalPage"></span>页,共<span class="totalCount"></span>条 '
		+'				<input	type="hidden" value="5" class="pageSize" />'
		+'				<button class="btn btn-default input-sm btnToPage">转</button>'
		+'			</div></li>'
		+'	</ul></nav>',
	pagerTemplate:'<nav><ul class="pagination" style="margin:0px;">'
			+'		<li><a href="javascript:void(0)" class="btnFirst">首页</a></li>'
			+'		<li><a href="javascript:void(0)" class="btnPre">上一页</a></li>'
			+'		<li><a href="javascript:void(0)" class="btnNext">下一页</a></li>'
			+'		<li><a href="javascript:void(0)" class="btnLast">尾页</a></li>'
			+'		<li><div style="padding: 2px 5px; float: left">'
			+'				<input type="text" maxlength="5" onkeyup="this.value=this.value.replace(/\D/g,\'\');"'
			+'					style="width: 50px; display: inline-block;" class="input-sm form-control pageNo"/>'
			+'					页/<span class="totalPage"></span>页,共<span class="totalCount"></span>条,每页 '
			+'				<input	type="text" maxlength="3" onkeyup="this.value=this.value.replace(/\D/g,\'\');"'
			+'					style="width: 50px; display: inline-block;" class="input-sm form-control pageSize" />'
			+'				<button class="btn btn-default input-sm btnToPage">转</button>'
			+'			</div></li>'
			+'	</ul></nav>',
		renderPager:function(){
			var $pager=this.$pager=$(this.setting.page.mini?this.miniPagerTemplate:this.pagerTemplate);
			this.$pageNo=$pager.find('.pageNo');
			this.$totalCount=$pager.find('.totalCount');
			this.$totalPage=$pager.find('.totalPage');
			this.$pageSize=$pager.find('.pageSize');
		},
		renderTable:function(){
			var html=[];
			html.push('<div style="min-height: '+this.setting.minHeight+';">');
			html.push('		<table class="table table-hover" style="margin-bottom:10px;">');
			html.push('			<thead>');
			html.push('				<tr class="headRow">');
			if(this.setting.checkOpt)
				html.push('					<th><input type="checkbox" class="allCheck"></th>');
			else 
				html.push('<th></th>');
			$.each(this.setting.columns,function(){
				html.push('					<th>'+this.title+'</th>');
			});
			if(this.setting.buttons&&this.setting.buttons.length>0)
				html.push('					<th>操作</th>');
			html.push('				</tr>');
			html.push('			</thead>');
			html.push('			<tbody>');
			html.push('			</tbody>');
			html.push('		</table>');
			html.push('	</div>');
			this.$table=$(html.join(''));
			this.$tableBody=this.$table.find('table tbody');
		},
		getProperty:function(obj,path){
			var paths=path.split("."),res=obj,i=0;
			do{
				res=res[paths[i++]];
			}while(i<paths.length&&res);
			return res!=null?res:'';
		},
		renderRecord:function(record){
			var html=[],keyColumn=this.setting.keyColumn,that=this;
			html.push('<tr>');
			//check框
			if(this.setting.checkOpt)
				html.push('<td><input type="checkbox" name="selectInput" value="'+record[keyColumn]+'"></td>');
			else if(this.setting.radioOpt)
				html.push('<td><input type="radio" name="selectInput" value="'+record[keyColumn]+'"></td>');
			else
				html.push('<td></td>');
			//普通列
			$.each(this.setting.columns,function(){
				var text=that.getProperty(record, this.code);
				this.render&&(text=this.render(text,record));
				html.push('					<td>'+text+'</td>');
			});
			//操作按钮列
			if(this.setting.buttons&&this.setting.buttons.length>0)
			{
				html.push('<td>');
				$.each(this.setting.buttons,function(){
					var showFlag=true;
					if(this.show)
						showFlag=this.show(record);
					if(!showFlag)
						return;
					html.push('					<button type="button" key="'+record[keyColumn]+'"'
							+'class="'+this.type+' btn btn-xs">'+this.name+'</button>');
				});
				html.push('</td>');
			}	
			html.push('</tr>');
			this.$tableBody.append(html.join(''));
		},
		bind:function(){
			var that=this;
			//操作按钮的事件，buttons:[{name,type,onclick:function(record){}}],
			this.setting.buttons&&$.each(this.setting.buttons,function(){
				var buttonConfig=this;
				this.onclick&&that.$tableBody.on('click','.'+this.type,function(){
					var $button=$(this),
						record=that.data.map[$button.attr('key')];
					buttonConfig.onclick(record);
					return false;
				});
			});
			//分页的事件
			if(this.setting.page.enable)			
			{
				//btnFirst,btnPre,btnNext,btnLast,btnToPage
				this.$pager.on('click','.btnFirst',function(){
					if(that.data.page.pageNo==1)
						return false;
					that.data.page.pageNo=1;
					that.load();
					return false;
				});
				this.$pager.on('click','.btnPre',function(){
					if(that.data.page.pageNo==1)
						return false;
					that.data.page.pageNo=that.data.page.prePage;
					that.load();
					return false;
				});
				this.$pager.on('click','.btnNext',function(){
					if(that.data.page.pageNo==that.data.page.totalPage)
						return false;
					that.data.page.pageNo=that.data.page.nextPage;
					that.load();
					return false;
				});
				this.$pager.on('click','.btnLast',function(){
					if(that.data.page.pageNo==that.data.page.totalPage)
						return false;
					that.data.page.pageNo=that.data.page.totalPage;
					that.load();
					return false;
				});
				this.$pager.on('click','.btnToPage',function(){
					that.data.page.pageNo=that.$pageNo.val();
					that.load();
					return false;
				});
			}
			//列点击事件
			this.$tableBody.on('click','tr',function(event){
				var $check=$('input[name=selectInput]',$(this)),
					check=$check.prop('checked'),
					record=that.data.map[$check.val()],
					selector=event.target.type!="checkbox"&&event.target.type!="radio";
				
				selector&&$check.prop('checked',!check);
				that.setting.onClickRecord&&that.setting.onClickRecord(selector?!check:check,record);
			});
			//复选框事件allCheck
			this.setting.checkOpt&&this.$table.on('click','.allCheck',function(event){
				var flag=this.checked;
		   		$.each(that.$table.find('td input:checkbox'),function(index,ele){
					if(ele.checked!=flag)
						$(ele).prop('checked',flag);		
		       	});
			});
		},
		refine:function(data,page,param){
			/**list:[];
			 * map:<key,record>;
			 * page:totalPage,totalCount,pageSize,pageNo,nextPage,prePage;
			 * Param*/
			var that=this,_data=this.data;
			_data.list=data;
			_data.map={};
			$.each(data,function(){
				_data.map[this[that.setting.keyColumn]]=this;
			});
			
			_data.page||(_data.page={});
			if(this.setting.page.enable&&page)
			{
				var pageSize=_data.page.pageSize||page.pageSize,
					pageNo=_data.page.pageNo||page.pageNo;
				
				page.totalCount=page.totalCount||data.length||0;
				page.totalPage||(page.totalPage=Math.ceil(page.totalCount/pageSize));
				page.nextPage||(page.nextPage=pageNo+1<page.totalPage?pageNo+1:page.totalPage);
				page.prePage||(page.prePage=pageNo-1>1?pageNo-1:1);
				$.extend(_data.page,page);
			}
			param&&$.extend(_data.param,param);
		},
		selectRecord:function(keyArray){
			var that=this;
			this.$tableBody.find('[name=selectInput]').prop('checked',false);
			$.each(keyArray,function(){
				that.$tableBody.find('[name=selectInput]').filter('[value='+this+']').prop('checked',true);
			});
		},
		loadData:function(data){
			this.refine(data, {totalCount:data.length});
			this.fillGrid();
		},
		//查询接口
		load:function(param){
			if(!this.setting.dataURL)
				return;
			
			//根据param、pager查询,dataURL
			var queryParam={},that=this;
			if(this.setting.page.enable)
			{
				this.data.page.pageSize=this.$pageSize.val();
				queryParam.pageSize=this.data.page.pageSize;
				queryParam.pageNo=this.data.page.pageNo;
			}
			param&&(this.data.param=param);
			this.data.param&&$.extend(queryParam,this.data.param);
			$.ajax(this.setting.dataURL,{
				type:'POST',
				data:queryParam,
				dataType:'json'
			}).done(function(data){ 
				that.refine(data.list||[], {totalCount:data.totalCount});
				that.fillGrid();
				that.setting.afterLoadData&&that.setting.afterLoadData();
				if(that.data.page.pageNo>1&&(data.list==null||data.list.length==0))
				{
					that.data.page.pageNo=1;
					that.load();
				}	
			}).fail(function(){
			});
		},
		//用data填充grid
		fillGrid:function(){
			var that=this;
			//填充table
			this.$tableBody.empty();
			this.data.list&&$.each(this.data.list,function(){
				that.renderRecord(this);
			});
			//填充pager
			this.$pageNo.val(this.data.page.pageNo);
			this.$pageSize.val(this.data.page.pageSize);
			this.$totalCount.text(this.data.page.totalCount);
			this.$totalPage.text(this.data.page.totalPage);
		},
		sync:function(){
			this.fillGrid();
			if(!this.data.list||this.data.list.length==0)
				this.load();
		},
		init:function(){
			this.render();
			this.bind();
			this.sync();
		}
	};
	return PageGrid;
}));
/**
 *<div class="PageGrid">
	<div style="min-height: 430px;">
		<table class="table table-hover" id="schemaList">
			<thead>
				<tr>
					<th><input type="checkbox" id="allCheck"></th>
					<th>协议名称</th>
					<th>协议编码</th>
					<th>类型</th>
					<th>备注</th>
					<th>操作</th>
				</tr>
			</thead>
			<tbody>
				<tr>
					<td><input type="checkbox" name="deleteId"
						value="${ele.schemaId!}"></td>
					<td>dsfsdfsdf</td>
					<td>ele.schemaCode!}</td>
					<td>接口协议</td>
					<td>le.schemaMemo!}</td>
					<td>
						<button type="button" schemaId="${ele.schemaId!}"
							class="btnView btn btn-xs">查看</button>
						<button type="button" schemaId="${ele.schemaId!}"
							class="btnEdit btn btn-xs">编辑</button>
					</td>
				</tr>
			</tbody>
		</table>
	</div>
	<nav>
		<ul class="pagination">
			<li><a href="javascript:void(0)" class="btnFirst">首页</a></li>
			<li><a href="javascript:void(0)" class="btnPre">上一页</a></li>
			<li><a href="javascript:void(0)" class="btnNext">下一页</a></li>
			<li><a href="javascript:void(0)" class="btnLast">尾页</a></li>
			<li><div style="padding: 2px 5px; float: left">
					<input type="text" maxlength="5" onkeyup="this.value=this.value.replace(/\D/g,\'\');"
						style="width: 50px; display: inline-block;" class="input-sm form-control pageNo"/>
						页/<span class="totalPage"></span>页,共<span class="totalCount"></span>条,每页 
					<input	type="text" maxlength="3" onkeyup="this.value=this.value.replace(/\D/g,\'\');"
						style="width: 50px; display: inline-block;" class="input-sm form-control pageSize" />
					<button class="btn btn-default input-sm btnToPage">转</button>
			</div>
			</li>
		</ul>
		
	</nav>
</div> 
 */
